package com.ctl.starter.all;

import com.ctl.StarterApplication;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.AnnotationBeanNameGenerator;

import java.beans.Introspector;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
//public class SafeBeanNameGenerator implements BeanNameGenerator {
public class SafeBeanNameGenerator extends AnnotationBeanNameGenerator {
    static Map<String,String> map =new ConcurrentHashMap<>();
    @Override
    public String generateBeanName(BeanDefinition definition, BeanDefinitionRegistry registry) {
        String[] beanDefinitionNames = registry.getBeanDefinitionNames();

        for (String beanDefinitionName : beanDefinitionNames) {
//            System.out.println(beanDefinitionName);
            try {
                map.put(registry.getBeanDefinition(beanDefinitionName).getBeanClassName(),beanDefinitionName);
            } catch (Exception e) {
                log.debug("beanDefinitionName={}",beanDefinitionName);
                return super.generateBeanName(definition, registry);
            }
        }
        String className = definition.getBeanClassName();
        String shortName = Objects.requireNonNull(className).substring(className.lastIndexOf('.') + 1);
//        if (shortName.equals("TestApplication")) {
////            return Introspector.decapitalize(shortName);
//            log.debug("beanName={},selfBeanName={}",className,"TestApplication");
//            return "TestApplication";
//        }
//        if (shortName.equals("ModelApplication")) {
////            return Introspector.decapitalize(shortName);
//            log.debug("beanName={},selfBeanName={}",className,"ModelApplication");
//            return "ModelApplication";
//        }
//        if (shortName.equals("StarterApplication")) {
//            log.debug("beanName={},selfBeanName={}",className,"/");
//            return "/";
//        }
        try {
            String[] beanNamesForType =null;
            if(StarterApplication.getConfigurableApplicationContext()!=null){
                beanNamesForType=StarterApplication.getConfigurableApplicationContext().getBeanNamesForType(Class.forName(definition.getBeanClassName()));
                return beanNamesForType[0];
            }else {
                log.debug("beanName={},selfBeanName={}",className,super.generateBeanName(definition, registry));
                return super.generateBeanName(definition, registry);
            }
        } catch (Exception e) {
             return Introspector.decapitalize(shortName);
        }
    }
}